package basic.concurrent;

import java.util.concurrent.*;

/**
 * concurrent 包中的线程池  可重用
 * USER: lintc 【lintiancong@zhuojianchina.com】
 * DATE: 2017/5/26 9:49
 */
public class ExecutorTest {
    public static void main(String[] args) {
        executorCompletionServiceTest();
    }
    /**
     * cachedThreadPool
     * 大小可变
     */
    public static void cachedThreadPoolTest() {
        ExecutorService service = Executors.newCachedThreadPool();
//        service.
    }
    /**
     * FixedThreadPool
     * 固定同步运行线程个数
     */
    /**
     * ScheduledThreadPool
     * 延迟执行
     */
    /**
     * SingleThreadPool
     * 单线程
     */


    /**
     * executorCompletionService
     * take 按照任务完成顺序 获取结果
     */
    public static void executorCompletionServiceTest() {
        ExecutorService executor = Executors.newCachedThreadPool();
        ExecutorCompletionService<String> service = new ExecutorCompletionService<>(executor);

        for (int i = 0; i < 5; i++) {
            final int x = i;
            service.submit(() -> {
                System.out.println(x);
                Thread.currentThread().sleep(1000 * (5 - x));
                return "x" + x;
            });
        }
        try {
            for(int i = 0; i < 5;i++ ) {
                System.out.println(service.take().get());
            }
        } catch(InterruptedException | ExecutionException e) {
        }
        executor.shutdown();
    }

    /**
     * future
     * 线程池结果接收
     * 对应 callable
     */
}
